// 接口配置
let baseUrl = 'http://接口域名/'
const uploadPresignedUrl = '获取上传签名/get-upload-token'
const batchUploadPresignedUrl = '批量获取上传签名/get-batch-upload-token'
const getFileUrl = '获取文件下载地址/get-file-url'
const postBatchFileUrl = '批量获取文件下载地址/post-batch-file-url'
const headerAuthName = 'token'
const getSignCode = '获取签名随机数(signCode)/sign-code'
const getFileUrlBySign = '获取文件下载地址(signCode)/get-file-url'
const postBatchFileUrlBySign = '批量获取文件下载地址(signCode)/post-batch-file-url'
const secretKey = '密钥(signCode)'

// 接口配置/京师书法小程序
// import APIConfig from '../../config/api.js'
// let baseUrl = (APIConfig.baseUrl || '') + '/sf-base/'
// const uploadPresignedUrl = 'file-v2/upload-sign'
// const batchUploadPresignedUrl = 'file-v2/get-batch-upload-token'
// const getFileUrl = 'file-v2/get-file-url'
// const postBatchFileUrl = 'file-v2/post-batch-file-url'
// const headerAuthName = 'token'
// const getSignCode = 'signature-access/file-v2/sign-code'
// const getFileUrlBySign = 'signature-access/file-v2/get-file-url'
// const postBatchFileUrlBySign = 'signature-access/file-v2/post-batch-file-url'
// const secretKey = 'pX6aX7sF8qK6lK8bT6'

// 获取文件MIME类型
const getContentType = (fileName) => {
  fileName = fileName || '';
  const ext = fileName.split('.').pop().toLowerCase();
  const typeMap = {
    jpg: 'image/jpeg',
    jpeg: 'image/jpeg',
    png: 'image/png',
    gif: 'image/gif',
    mp4: 'video/mp4',
    mp3: 'audio/mp3',
    wav: 'audio/wav',
    ogg: 'audio/ogg',
    pdf: 'application/pdf',
    doc: 'application/msword',
    docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    xls: 'application/vnd.ms-excel',
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    ppt: 'application/vnd.ms-powerpoint',
    pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    zip: 'application/zip',
    rar: 'application/x-rar-compressed',
    txt: 'text/plain',
    json: 'application/json'
  };
  return typeMap[ext] || 'application/octet-stream';
};

export default {
  /**
   * 上传文件到 cos
   * @param {Object} params 包含 file 和 isShare 参数
   */
  upload(params) {
    let file = params.file;
    let isShare = !!params.isShare;
    if (!file) { return Promise.reject('参数不能为空！') }
    if (!file.name) { params.fileName = file.name = (file.tempFilePath || file.url).split('/').pop(); }
    let _this = this;
    return _this.getUploadKey(file, isShare)
      .then((keyInfo) => { // keyInfo:{resourceKey,fileName,signUrl}
        params.keyInfo = keyInfo;
        return _this.uploadFileByKey(params);
      })
      .catch((error) => {
        return Promise.reject(error);
      })
  },
  uploadFileByKey(params) {
    let file = params.file;
    let keyInfo = params.keyInfo || {};
    let progressCallback = params.progressCallback || null;
    return new Promise(async (resolve, reject) => {
      // 如果是 base64 字符串，转成 File 对象
      if (typeof file === 'string') {
        file = await this.base64ToFile(file, params.fileName);
      }
      // 读取文件内容并转换为 ArrayBuffer
      wx.getFileSystemManager().readFile({
        filePath: file.url || file.tempFilePath || file,
        success: (fileRes) => {
          let fileName = file.name || file.fileName || (file.url || file.tempFilePath).split('/').pop();
          wx.request({
            url: keyInfo.signUrl,
            method: 'PUT',
            header: {
              'Content-Type': getContentType(fileName),
            },
            data: fileRes.data,
            enableChunked: !!progressCallback, // 启用分片上传（支持进度监听）
            onProgressUpdate: (res) => {
              console.log('上传进度:', res.progress); // 进度百分比（0-100）
              console.log('已上传:', res.totalBytesSent); // 已上传字节数
              console.log('总大小:', res.totalBytesExpectedToSend); // 总字节数
              if (progressCallback) progressCallback(res); // 调用外部回调
            },
            success(res) {
              if (res.statusCode === 200) {
                resolve(keyInfo);
              } else {
                reject('文件上传失败！');
              }
            },
            fail(err) {
              reject(err);
            }
          });
        },
        fail: (readErr) => {
          reject(readErr);
        }
      });
    })
  },
  // 从服务端获取上传签名信息-单个
  getUploadKey(file, isShare = false) {
    const reqUrl = baseUrl + uploadPresignedUrl;
    const originalName = file.name || file.fileName;
    return new Promise((resolve, reject) => {
      wx.request({
        url: reqUrl,
        method: 'POST',
        data: {
          originalName: originalName,
          share: isShare,
          platform: 'file_cos'
        },
        header: {
          [headerAuthName]: wx.getStorageSync(headerAuthName),
          'Content-Type': 'application/json'
        },
        success(res) {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(res.data.message || '获取上传签名信息失败！');
          }
        },
        fail(err) {
          reject(err);
        }
      })
    });
  },
  // 从服务端获取上传签名信息-批量
  getBatchUploadKey(fileArr, isShare = false) {
    const reqUrl = baseUrl + batchUploadPresignedUrl;
    const fileNames = [];
    for (let i = 0; i < fileArr.length; i++) {
      fileNames.push(fileArr[i].name || fileArr[i].fileName);
    }
    return new Promise((resolve, reject) => {
      wx.request({
        url: reqUrl,
        method: 'POST',
        data: {
          originalNames: fileNames,
          share: isShare
        },
        header: {
          [headerAuthName]: wx.getStorageSync(headerAuthName),
          'Content-Type': 'application/json'
        },
        success(res) {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(res.data.message || '获取上传签名信息失败！');
          }
        },
        fail(err) {
          reject(err);
        }
      })
    })
  },
  // 批量获取文件下载地址
  getBatchFileUrl(fileNames) {
    const reqUrl = baseUrl + postBatchFileUrl
    if (fileNames.length === 0) { return Promise.resolve([]) }
    return new Promise((resolve, reject) => {
      wx.request({
        url: reqUrl,
        method: 'POST',
        data: {
          fileNames: fileNames,
          expiration: 86400000
        },
        header: {
          [headerAuthName]: wx.getStorageSync(headerAuthName),
          'Content-Type': 'application/json'
        },
        success(res) {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(res.data.message || '获取文件下载地址失败！');
          }
        },
        fail(err) {
          reject(err);
        }
      })
    })
  },
  getFileUrl(fileName, isShare = false) {
    const reqUrl = baseUrl + getFileUrl
    if (!fileName) { return Promise.reject('参数不能为空！') }
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${reqUrl}?expiration=86400000&share=${isShare || false}&fileName=${fileName}`,
        method: 'GET',
        header: {
          [headerAuthName]: wx.getStorageSync(headerAuthName)
        },
        success(res) {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(res.data.message || '获取文件下载地址失败！');
          }
        },
        fail(err) {
          reject(err);
        }
      })
    })
  },
  // base64 转换为 file 类型
  base64ToFile(base64Str, fileName = 'image.png') {
    // 分离base64数据和类型信息
    const arr = base64Str.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    // 转换为Uint8Array
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }

    // 在小程序中，我们通常需要的是临时文件路径，用于上传等操作
    return new Promise((resolve, reject) => {
      // 将二进制数据写入临时文件
      wx.getFileSystemManager().writeFile({
        filePath: wx.env.USER_DATA_PATH + '/' + fileName,
        data: u8arr,
        encoding: 'binary',
        success(res) {
          // 返回临时文件路径和相关信息，模拟File对象
          resolve({
            path: wx.env.USER_DATA_PATH + '/' + fileName,
            name: fileName,
            type: mime,
            size: u8arr.length
          });
        },
        fail(err) {
          reject(err);
        }
      });
    });
  }
}
